const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const fs = require('fs')

function writeFile(event, data) {
    fs.writeFileSync('E:/hello.txt', data)
}

function readFile() {
    return fs.readFileSync('E:/hello.txt').toString()
}

const createWindow = () => {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.resolve(__dirname, './preload.js')
        }
    })

    ipcMain.on('file-save', writeFile)
    ipcMain.handle('file-read', readFile)

    win.loadFile('./pages/index.html')

    setTimeout(() => {
        win.webContents.send('message', 'app loaded')
    }, 6000)
}

app.whenReady().then(() => {
    createWindow()

    app.on('window-all-closed', () => {
        if (process.platform !== 'darwin') app.quit()
    })

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})